<?php
/**
 * multiple_resource_copy.php 
 * 
 * @copyright &copy; 2006-2007 The Open University
 * @author a.p.carter AT open.ac.uk, T.J.Hunt@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 */

require_once('../../config.php');
require_once("$CFG->libdir/moodlelib.php");
 
// copy or move multiple resource items from one resourcepage to another, or delete multiple items.

$idlist=required_param('idlist', PARAM_RAW);  // ids of resources to be moved/copied 
$rpidlist=optional_param('destination', array(), PARAM_RAW);  // ids of resourcepages to be moved/copied to 
$cmid=required_param('cmid',PARAM_INT);    // Course Module ID
$currentrpid = optional_param('rpid',PARAM_INT);	// calling resource page id
$courseid = optional_param('courseid',PARAM_INT);	// calling course id

$copyto=optional_param('copyto',null,PARAM_ALPHANUM);  // copy to indicator
$moveto=optional_param('moveto',null,PARAM_ALPHANUM);  // move to indicator
$delete=optional_param('delete',null,PARAM_ALPHANUM);  // move to indicator

// Get the singleton instance of the resourcepage module, and get this resourcepage.
require_once("module_resourcepage.php");
$module=module_resourcepage::$inst;
$module->obtain_view_info($cmid,0,$cm,$course,$resourcepage);
$module->verify_edit_action($cm);

// Make sure some items were selected.
if( empty($idlist) ){
    redirect($CFG->wwwroot . '/mod/resourcepage/view.php?id=' . $cmid);
}
$idlist = trim($idlist, ',');
$containeritems = explode(',', $idlist);

// Deal with deletion first.
if ($delete) {
    foreach ($containeritems as $item) {
        $ids = explode('_', $item);
        // check if it is a section we're deleting
        if(substr($ids[1],0, 1) == 's') { 
            $sourcecontainer = substr($ids[1], 1);
            $sourcecontainerparent = $ids[0];
            
            // move the sections to be deleted to the resource page's deleted container
            move_resourcepage_section($sourcecontainerparent, $sourcecontainer, $module, $resourcepage->deletedcontainerid);
        }
        $containerid = $ids[0];
        $itemid = $ids[1];
        $module->move_container_item($containerid, $itemid, $resourcepage->deletedcontainerid);
    }
    add_to_log($courseid, "resourcepage", "deleteitems", "view.php?id=$cmid", "Deleted #", $cmid);
    redirect($CFG->wwwroot . '/mod/resourcepage/view.php?id=' . $cmid);
}

// Validate target page.
$size = sizeof($rpidlist);
$actualsize = 0;

for ($i = 0; $i < $size; $i++) {
	if(  empty($rpidlist[$i]) ) {
		// do nothing	
	} else {
		$actualsize++;
	} // endif
} // endfor

$size = sizeof($rpidlist);

if(!$delete && $actualsize == 0) {
 	// we have nothing to play with - get outa here
 	$rpidlistname = 'destination';
 	error('A required parameter ('.$rpidlistname.') was missing');

} else {
	if($actualsize < $size) {
		// the first element requires rmoving has it contains no value
		$rpids = array_slice($rpidlist, 1, $actualsize);
	} else {
		$rpids = $rpidlist;
	} // endif
} // endif

// if we have got here we are all okay

// see bug 3508
// file type items may contain more than one file 
// so make sure that we can copy each file across

require_once("resourcepage_copy_file.php");

// allow for mutiple copies/moves just in case needed
$destindex = 0; // default value
$len = sizeof($containeritems);

for ($i = 0; $i < $actualsize; $i++) {
	// just in case decide to do other things other than copy/move to
	// keep it down to individual if copy / if move statements
	
    $section = false;
    $topofpage = false;
    $bottomofpage = false;
    $otherpage = false;
	
    // check if the destination is a section within the current resource page
    if(substr($rpids[$i],0, 1) == 's') {
        $section = true;
    } else {
        if(substr($rpids[$i],0, 1) == 't') {
            $topofpage = true;
        } else {
            if(substr($rpids[$i],0, 1) == 'b') {
                $bottomofpage = true;
            } else {
                $otherpage = true;
            }
        }
    } // endif

    if($section) {
        $destcontainer = substr($rpids[$i],1);
        $destinationrpid = $currentrpid;
    } // endif
    
    if($otherpage) {
        // get destination resource page container id from destination resource page id
        $destinationrpid = $rpids[$i];
    }
    
    if($topofpage || $bottomofpage) {
        // we are looking to move to the top or bottom of the page
        $destinationrpid = $currentrpid; 
    }
    
    // not looking to move within a section within the current page, but to a new page or current page
    if(! $section) {
		$sql =  'select course, containerid from prefix_resourcepage where id = '.$destinationrpid;
		$rs = $module->do_sql($sql);
		// get destination container
		$destinationcourse = $rs->fields['course'];
		$destcontainer = $rs->fields['containerid'];
	}

	// process each item
    for($j = 0; $j < $len; $j++) {
        $containeritem = explode('_', $containeritems[$j]);

        // get source container and item
        // check if container item is a section
        if(substr($containeritem[1],0, 1) == 's') { 
            $sourcecontainer = substr($containeritem[1], 1);
            $sourcecontainerparent = $containeritem[0];          

            if(!empty($copyto) ) {
            	$tw=new transaction_wrapper();
                copy_resourcepage_section($sourcecontainerparent, $sourcecontainer, $module, $destcontainer);
                $tw->commit();            
            }

            if(!empty($moveto) ) {
                move_resourcepage_section($sourcecontainerparent, $sourcecontainer, $module, $destcontainer);
            }
            

        } else {
            $sourcecontainer = $containeritem[0];
            $sourceitem=$containeritem[1];

            if($otherpage) { 
                // copying or moving to another page
                if(!empty($copyto) ) {
                    // for each resource page item
                    copy_item($sourcecontainer, $sourceitem, $module, $destcontainer);
                } // endif
            
                if(!empty($moveto) ) {
                    move_item($sourcecontainer, $sourceitem, $module, $destcontainer, $cmid, $destindex);
                }

            } else {
                // copy or move to the top or bottom of the current page
                $dindex = 0; // default to bottom of page
                if($topofpage) {
                   $dindex = $j+1;
                }

                // copy item
                if(!empty($copyto) ) {
                    copy_item_within_page($sourcecontainer, $sourceitem, $module, $destcontainer, $cmid, $dindex);
                }

                // move item
                if(!empty($moveto) ) {
                    move_item($sourcecontainer, $sourceitem, $module, $destcontainer, $cmid, $dindex);
                }

            }// endif


        } // endif

    } // end inner for loop

	// code amended to deal with bug #3433 - Note assumes that there is only one destination 
	// for moved/copied items
	$sql = 'select cm.id from prefix_course_modules cm inner join prefix_modules m on cm.module=m.id where instance= '.$destinationrpid.' and name=\'resourcepage\'';
	$dcmids = $module->do_sql($sql);
	$dcmid = $dcmids->fields['id'];
} // endfor loop

// Log and return to view
    
if(!empty($copyto) ) {
    add_to_log($courseid, "resourcepage", "copyitem", "view.php?id=$cmid",
        "Copied #",$dcmid);
} // endif
    
if(!empty($moveto) ) {
    add_to_log($courseid, "resourcepage", "moveditem", "view.php?id=$cmid",
        "Moved #",$dcmid);
} // endif

// code amended to deal with bug #3433 - Note assumes that there is only one destination 
// for moved/copied items
redirect('view.php?id='.$dcmid);


    /**
 * Removes an item from one container then adds it to another (or possibly
 * to the same one again)
 * @param int $container ID of subcontainer's parent container
 * @param int $subcontainer ID of container being moved
 * @param int $newcontainer ID of target container
 * @param int $newseq Sequence in new container (leave 0/default to add to end)
 */
function copy_item($sourcecontainer, $sourceitem, $module, $destcontainer) {

global $CFG;

    $rcfarray = array();

    // need to get type of item and other details
    $sql =  'select * from prefix_resourcepage_items where id = '.$sourceitem;
        
    $rs = $module->do_sql($sql);

    $itemtype = $rs->fields['itemtype'];
    $title = $rs->fields['title'];
    $description = $rs->fields['description'];
    $pluginfo = $rs->fields['plugininfo'];
    $url = $rs->fields['weblink'];
    $crosslink = $rs->fields['crosslink'];
    $rights = $rs->fields['rights'];
    $data = $rs->fields['data'];

    // set up item flag if needed
    // can return 0, 1, or 2 rows
    $flagsql = 'select * from prefix_resourcepage_itemflags where itemid = '.$sourceitem;

    $flagrs = $module->do_sql($flagsql);
                
    $printeditem = false;
    $accessible = true;

    while(!$flagrs->EOF) {
        $flag = $flagrs->fields['flag'];

        if($flag == 'printeditem') {
            $printeditem = true;
        } // endif
        
        if($flag == 'inaccessible') {
            $accessible = false;
        } // endif
        
        $flagrs->MoveNext();
    } // endwhile

    // Do main part depending on type
    $copyableitem = true;
    switch ($itemtype) {
        case 'placeholder' : 
            // set moveable item to false
            $copyableitem = false;
            break;
            
        case 'file' :
            // get file details
            $fsql = 'select * from prefix_resourcepage_files where itemid = '.$sourceitem;
            $frs = $module->do_sql($fsql);
            
            // see bug 3508
            // file type items may contain more than one file 
            // so make sure that we can copy each file across
            
            while(! $frs->EOF) {
                $filepath = $frs->fields['filepath'];               
                $originalfilepath = $CFG->dataroot.'/'.$filepath;
                // code based on add_resourcepage_file() in moodle_setup_actions.php
                // Copy actual file
                if($filepath) {
                    // get destination course
                    $sql =  'select course from prefix_resourcepage where containerid = '.$destcontainer;
                    $rs1 = $module->do_sql($sql);
                    $destinationcourse = $rs1->fields['course'];
                    // copy file to new destination
                    $file = basename($filepath);
                    $relfilepath = $destinationcourse.'/moddata/resourcepage/'.$file;
                    $targetfilepath=$CFG->dataroot.'/'.$relfilepath;
                    $coursefiledir=dirname($targetfilepath);      
                    if(!mkdir_recursive($coursefiledir)) {
                        error ('Failed to make directory: '.$coursefiledir);
                    }  
                    
                    // if original file path is the same as target file path 
                    // do something see bug 3538
                    
                    // equally if we are unable to copy to a target file path 
                    // we need to do something
                    
                    if(file_exists($targetfilepath)) {
                        
                        // do nothing for the moment
                        
                        // we need to create a new file name to copy to
                        
                        // check to find names of all files in the $coursefiledir directory
                        // need to create a new targetfilepath
                        
                        $files1 = scandir($coursefiledir); 
                    
                        $n = 1;
                        $flen = count($files1);
                        for($b=0; $b < $flen; $b++) {
                        
                            if($files1[$b] == $file) {
                                
                                // create a new file name and re-test
                                
                                $splitarray = preg_split('/[.]/', $file);
                                 
                                // further split filename to get possible numeric value                                         

                                $crap = @preg_split("/_xyz/", $splitarray[0]); 
                                
                                // check to see what crap might hold
                                
                                if(count($crap) > 1) {

                                    // need to know whether crap remainder is a number or not

                                    if(is_numeric($crap[1]) ) {

                                        // since that numeric value is being used as part of the
                                        // _xyz value add 1 to it try and create an unused _xyz numeric value 

                                        $n = $crap[1]+1;

                                    } // endif 

                                } // endif 
                                
                                // further split the filename at _xyz
                                $filename = @preg_split("/_xyz[0-9]+/", $splitarray[0]);                                    
                                $filenameelements = @count($filename);                                                                              
                                $basicname = 'xxx'.$n;
                                
                                if($filenameelements > 0) {
                                    
                                    $basicname = $filename[0];
                                    
                                    
                                } else {
                                    
                                    $basicname = $splitarray[0];
                                    
                                }
                                    
                                    
                                $file = $basicname.'_xyz'.$n.'.'.$splitarray[1];                                    
                                $n++;
                                
                                
                            }
                                
                        }
                        
                        // re-create the $targetfilepath

                        $relfilepath = $destinationcourse.'/moddata/resourcepage/'.$file;
                        $targetfilepath=$CFG->dataroot.'/'.$relfilepath;
                                                    
                        
                    } // endif file exists
                    
                        
                    // copy file
                          
                    if(!@copy($originalfilepath,$targetfilepath)) {
                        error("Failed to copy file $filepath to $targetfilepath");
                    } // endif
                        

                    
                } // endif
                
                $rcf = new resourcepage_copy_file($filepath,$relfilepath, $targetfilepath);
                array_push($rcfarray, $rcf);
                
                $frs->MoveNext();
                
            } // endwhile loop
        
            break;

        default:
        
            // do nothing 
        
            break;
                            
    } // end switch-case statement


    if($copyableitem) {
            
        // copy to 
        $item=$module->add_item($itemtype,true,null,null,null,$title,$description,$pluginfo,$url,null,null,$crosslink, null, null, $rights,$data);
        
        if($printeditem) {
            $module->add_item_flag($item,'printeditem');
        }
        
        if(!$accessible) {
            $module->add_item_flag($item,'inaccessible');
        }
        
        
        // see bug 3508
        // file type items may contain more than one file 
        // so make sure that we can copy each file across
        
        $size = count($rcfarray);
        
        for($n = 0; $n < $size; $n++) {
            
            $rcf = $rcfarray[$n];                   
            $filepath = $rcf->get_filepath();  
            $relfilepath = $rcf->get_relfilepath(); 
            $targetfilepath = $rcf->get_targetfilepath(); 
                            
            // check to see whether filepath is set or not !!!!
            if(isset($filepath)) {
                $module->add_item_file($item,$relfilepath,
                        mimeinfo('type',$relfilepath),filesize($targetfilepath));
            }
        
        } // endfor
        
        $module->add_container_item($destcontainer,$item); 
        
                                        
    } // endif  
        
    $rcfarray = array();  // re-initialise the array

    return $item;
}


/**
 * Removes an item from one container then adds it to another (or possibly
 * to the same one again)
 * @param int $container ID of subcontainer's parent container
 * @param int $subcontainer ID of container being moved
 * @param int $newcontainer ID of target container
 * @param int $newseq Sequence in new container (leave 0/default to add to end)
 */
function move_item($sourcecontainer, $sourceitem, $module, $destcontainer, $cmid, $destindex) {

    $module->obtain_view_info($cmid,null,$cm,$course,$resourcepage);

    // Security check for editing this page
    $module->verify_edit_action($cm);

    // Verify item is within that container and container is within that module
    $module->verify_container_item_editable(
    array($resourcepage->containerid,$resourcepage->deletedcontainerid),
    $sourcecontainer,$sourceitem);

    // Move
    $module->move_container_item($sourcecontainer,$sourceitem,$destcontainer,$destindex);
}




function copy_item_within_page($sourcecontainer, $sourceitem, $module, $destcontainer, $cmid, $destindex) {

    // copy to bootom of page    
    $item = copy_item($sourcecontainer, $sourceitem, $module, $destcontainer);

    // Move to correct position if not required to be copied to the bottom of the page
    if($destindex > 0) {
        move_item($destcontainer,$item, $module, $destcontainer, $cmid, $destindex);
    }

}


/**
 * Copies a container from one container to another 
 * @param int $container ID of subcontainer's parent container
 * @param int $subcontainer ID of container being moved
 * @param int $newcontainer ID of target container
 * @param int $newseq Sequence in new container (leave 0/default to add to end)
 */
function copy_resourcepage_section($sourcecontainerparent, $sourcecontainer, $module, $destcontainer) {

    $query = "SELECT containertype FROM prefix_resourcepage_containers WHERE id = '".$sourcecontainer."'";
    $rs = $module->do_sql($query);
    $containertype = '';
    
    // should only be one row returned             
    while(!$rs->EOF) {               
        $containertype = $rs->fields['containertype'];
        $rs->MoveNext();
    }
    
    // Is the item a shared section
    if ($containertype == '_page') {
        
        // need to count the container items for the dest for the sequence
        $rs2 = $module->do_sql("SELECT COUNT(*) FROM modprefix_containeritems WHERE containerid = '".$destcontainer."'");
        $sequence = $rs2->fields['count']+1;

        $sql = "
INSERT INTO modprefix_containeritems (containerid, sequence, subcontainerid, hidden)
SELECT ".$destcontainer.",".$sequence.",".$sourcecontainer.", hidden
FROM modprefix_containeritems WHERE subcontainerid = '".$sourcecontainer."' AND containerid = '".$sourcecontainerparent."'";
        $module->do_sql($sql);
    } else {
    	// get the destination page id
    	$clause = "id='".$destcontainer."'";
        $destpage = get_records_select('resourcepage_containers',$clause);
        
        // get the data to clone into the new section
        $clause = "id='".$sourcecontainer."'";
        $sectiondata = get_records_select('resourcepage_containers',$clause);
        $sectiondata = $sectiondata[$sourcecontainer];
        $sectiondata->resourcepageid = $destpage[$destcontainer]->resourcepageid;
        unset($sectiondata->id);
        $newsectionid = insert_record('resourcepage_containers', $sectiondata, true);
    
        // add the section container to containeritems table
        $module->add_container_subcontainer($destcontainer,$newsectionid);  
   
    
    
		$clause = "containerid='".$sourcecontainer."'";
		$sort = "sequence ASC";
		$fields = 'sequence,containerid,itemid,subcontainerid,hidden'; 
	    $itemsrs = get_recordset_select('resourcepage_containeritems',$clause, $sort, $fields);
	    
	    while(!$itemsrs->EOF) {
	        if (isset($itemsrs->fields['itemid'])) {
	        	//copy_item();
	        	copy_item($sourcecontainer, $itemsrs->fields['itemid'], $module, $newsectionid);
	        } elseif (isset($itemsrs->fields['subcontainerid'])) {
	            $sourcecontainerparent = $sourcecontainer;
	            $sourcecontainer = $itemsrs->fields['subcontainerid'];
	            copy_resourcepage_section($sourcecontainerparent, $sourcecontainer, $module, $newsectionid);
	        }
	        $itemsrs->MoveNext();
	    }
    }
}



/**
 * Moves a container from one container to another
 * @param int $container ID of subcontainer's parent container
 * @param int $subcontainer ID of container being moved
 * @param int $newcontainer ID of target container
 * @param int $newseq Sequence in new container (leave 0/default to add to end)
 */
function move_resourcepage_section($sourcecontainerparent, $sourcecontainer, $module, $destcontainer) {

	$tw=new transaction_wrapper();
	
	$query = "SELECT containertype FROM prefix_resourcepage_containers WHERE id = '".$sourcecontainer."'";
    $rs = $module->do_sql($query);
    $containertype = '';
    
    // should only be one row returned             
    while(!$rs->EOF) {               
        $containertype = $rs->fields['containertype'];
        $rs->MoveNext();
    }
    
    // Is the item a shared section
    if ($containertype == '_page') {
    	// dont move a shared section to the page it being shared from
        if ($sourcecontainer != $destcontainer) {
            $module->move_container_subcontainer($sourcecontainerparent,$sourcecontainer,$destcontainer);
        } else {
            error('You cannot move a shared section to the resource page it is being shared from');	
        }
        
    } else {

		// need to get the destination page id
		$clause = "id='".$destcontainer."'";
	    $targetpage = get_records_select('resourcepage_containers',$clause);
	    $destpage = $targetpage[$destcontainer]->resourcepageid;
		
	    // move a section subcontainer in the containeritems table from one container to another. 
	    $module->move_container_subcontainer($sourcecontainerparent,$sourcecontainer,$destcontainer);
	    
	    // need to change the resoucepageid in the containers table of all moved containers to
	    // the destpage id... start by creating an array of containers ids to change
	    $rssubcontainers = $module->get_all_subcontainers($sourcecontainer);
	    $subarray[] = $sourcecontainer;
	    while(!$rssubcontainers->EOF) {
	       $subarray[] = $rssubcontainers->fields['subcontainerid'];
	       $rssubcontainers->MoveNext();
	    }
	    
	    // loop through the container ids array and update the containers with the new $destpage
	    foreach ($subarray as $containerid) {
		    $sql = 'select * from modprefix_containers where id = '.$containerid; 
		               
		    $rs = $module->do_sql($sql);
		                
		    // should only be one row return
		                
		    while(!$rs->EOF) {               
		        $id = $rs->fields['id'];
		        $containertype = $rs->fields['containertype'];
		        $nextupdate = $rs->fields['nextupdate'];
		        $plugininfo = $rs->fields['plugininfo'];
		        $title = $rs->fields['title'];
		        $resourcepageid = $rs->fields['resourcepageid'];
		                
		        $module->upd_container($containerid, $containertype, $nextupdate, $plugininfo, $title, $destpage);
		
		        $rs->MoveNext();
		    } // endwhile loop
	    }
	    
    }
    $tw->commit();
}
?>
